package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.Dept;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private DeptMapper deptMapper;


    /**
     * 分页查询用户列表
     * @param pageNum
     * @param pageSize
     * @param userDto
     * @return
     */
    @Override
    public PageResponse<UserVo> getUserList(Integer pageNum, Integer pageSize, UserDto userDto) {
        if (pageNum == null || pageSize == null || userDto.getDeptNo() ==null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        User user = BeanUtil.toBean(userDto, User.class);
        //处理部门编号
        user.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        user.setIsDelete(0); //设置查询未删除的用户

        //设置起始分页
        PageHelper.startPage(pageNum,pageSize);
        //条件查询用户列表
        List<UserVo> users = userMapper.selectUserList(user);

        //遍历用户列表
        users.forEach(userVo -> {
            //查询每一个用户绑定的所有角色
            List<RoleVo> roleVos = userRoleMapper.selectUserRoleByUserId(userVo.getId());

            //设置角色编号集合
            Set<String> roleIds = roleVos.stream().map(RoleVo::getRoleId).collect(Collectors.toSet());
            userVo.setRoleVoIds(roleIds);
            //设置角色名称集合
            Set<String> roleLabels = roleVos.stream().map(RoleVo::getRoleName).collect(Collectors.toSet());
            userVo.setRoleLabels(roleLabels);

            //设置角色列表
            userVo.setRoleList(roleVos);

        });

        Page<UserVo> page = (Page<UserVo>) users;
        //返回数据
        return PageResponse.of(page,UserVo.class);
    }

    /**
     * 新增用户
     * @param userDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserDto userDto) {
        if (userDto == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        //查询用户名和邮箱是否存在
        List<User> users = userMapper.selectByRealNameOreEail(userDto.getRealName(),userDto.getEmail());
        if (users != null || users.size() != 0) {
            throw new BaseException(BasicEnum.ADD_USER_FAILED);
        }

        //判断所选的部门是否为最底层部门
        List<Dept> depts = deptMapper.selectDeptByParenNo(NoProcessing.processString(userDto.getDeptNo()));
        if (depts != null && depts.size() != 0) {
            throw new RuntimeException("请选择最底层部门");
        }

        User user = BeanUtil.toBean(userDto, User.class);
        //封装属性
        String password = "888itcast.CN764%...";  //默认密码
        //密码加密处理
        user.setPassword(BCrypt.hashpw(password,BCrypt.gensalt()));
        user.setDataState(SuperConstant.DATA_STATE_0); //账号状态正常
        user.setUsername(userDto.getEmail());
        user.setIsDelete(0); //设置用户账号未删除
        userMapper.insertUser(user);

        //创建存储用户角色关联的对象集合
        List<UserRole> userRoles = new ArrayList<>();
        //遍历角色编号
        userDto.getRoleVoIds().forEach(roleId->{
//            UserRole userRole = new UserRole();
//            userRole.setUserId(user.getId());
//            userRole.setRoleId(Long.valueOf(roleId));
//            userRole.setDataState(SuperConstant.DATA_STATE_0);

            //封装数据
            UserRole userRole = UserRole.builder()
                    .roleId(Long.valueOf(roleId))
                    .userId(user.getId())
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            //添加到集合中
            userRoles.add(userRole);
        });

        //添加到用户角色关联表中
        userRoleMapper.insertUserRole(userRoles);

    }

    /**
     * 更新用户信息
     * @param userDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserDto userDto) {
        if (userDto == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        User user = BeanUtil.toBean(userDto, User.class);
        //更新用户信息
        userMapper.updateUser(user);

        //更新用户角色信息
        //1、先删除原有的角色信息
        userRoleMapper.deleteByUserId(userDto.getId());
        //2、再重新添加关联的角色信息
        List<UserRole> userRoles = new ArrayList<>();
        userDto.getRoleVoIds().forEach(roleId->{
            //封装数据
            UserRole userRole = UserRole.builder()
                    .roleId(Long.valueOf(roleId))
                    .userId(user.getId())
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            //添加到集合中
            userRoles.add(userRole);
        });
        userRoleMapper.insertUserRole(userRoles);
    }

    /**
     * 查询当前用户
     * @return
     */
    @Override
    public UserVo getCurrentUser() {
        //从当前请求线程中获取用户id
        Long userId = UserThreadLocal.getUserId();

        //查询用户信息
        User user = userMapper.selectUserById(userId);

        //查询关联的角色信息
        List<RoleVo> roleVos = userRoleMapper.selectUserRoleByUserId(userId);
        Set<String> roleNames = roleVos.stream().map(RoleVo::getRoleName).collect(Collectors.toSet());
        Set<String> roleIds = roleVos.stream().map(RoleVo::getRoleId).collect(Collectors.toSet());


        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        //设置角色名称集合
        userVo.setRoleLabels(roleNames);
        userVo.setRoleNames(roleNames);
        //设置角色id集合
        userVo.setRoleVoIds(roleIds);
        userVo.setRoleList(roleVos);

        return userVo;
    }

    /**
     * 修改用户状态信息
     * @param id
     * @param status
     */
    @Override
    public void updateUserStatus(Long id, String status) {
        if (id == null || status == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        User user = User.builder().dataState(status).build();
        user.setId(id);
        //修改状态
        userMapper.updateUser(user);
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        if (id == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        //查询账号状态，如果是启用状态不能删除
        User user0 = userMapper.selectUserById(id);
        if (user0.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new BaseException(BasicEnum.MENU_ENABLE);
        }

        //封装属性
        User user = User.builder()
                .isDelete(1) // 设置为1，表示删除当前用户账号
                .build();
        user.setId(id);

        //修改用户信息
        userMapper.updateUser(user);
    }

    /**
     * 账号密码重置
     * @param userId
     */
    @Override
    public void updatePassWord(Long userId) {
        if (userId == null) {
            throw new BaseException(BasicEnum.PARAM_ERROR);
        }

        //设置初始密码
        String password = "888itcast.CN764%...";
        //加密处理
        password = BCrypt.hashpw(password, BCrypt.gensalt());

        //修改密码
        userMapper.updatePassWord(userId,password);
    }
}
